<template>
  <div class="user-list">
    <div class="header">
      <h2>用户管理</h2>
      <el-button type="primary" @click="handleCreate" v-if="hasCreatePermission">
        <el-icon><Plus /></el-icon>
        创建用户
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <el-form :model="searchForm" inline>
        <el-form-item label="搜索">
          <el-input
            v-model="searchForm.search"
            placeholder="用户名、邮箱、真实姓名"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
            <el-option label="启用" value="ACTIVE" />
            <el-option label="禁用" value="INACTIVE" />
            <el-option label="封禁" value="BANNED" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.roleId" placeholder="选择角色" clearable>
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 用户列表 -->
    <el-table
      :data="userList"
      v-loading="loading"
      stripe
      style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="头像" width="80">
        <template #default="{ row }">
          <el-avatar :src="row.avatar" :size="40">
            {{ row.username?.charAt(0)?.toUpperCase() }}
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="realName" label="真实姓名" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag
            :type="getStatusType(row.status)"
            size="small"
          >
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="角色" width="200">
        <template #default="{ row }">
          <el-tag
            v-for="userRole in row.userRoles"
            :key="userRole.role.id"
            size="small"
            style="margin-right: 4px"
          >
            {{ userRole.role.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="lastLoginAt" label="最后登录" width="180">
        <template #default="{ row }">
          {{ formatDate(row.lastLoginAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleView(row)" v-if="hasPermission(ALL_PERMISSIONS.USER_READ)">
            查看
          </el-button>
          <el-button size="small" type="primary" @click="handleEdit(row)" v-if="hasEditPermission">
            编辑
          </el-button>
          <el-button 
            size="small" 
            type="success" 
            @click="handleEnable(row)" 
            v-if="hasEnablePermission && row.status !== 'ACTIVE'"
          >
            启用
          </el-button>
          <el-button 
            size="small" 
            type="warning" 
            @click="handleDisable(row)" 
            v-if="hasDisablePermission && row.status === 'ACTIVE'"
          >
            禁用
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)" v-if="hasDeletePermission">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.limit"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="userDetailVisible"
      title="用户详情"
      width="600px"
    >
      <div v-if="selectedUser">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户名">{{ selectedUser.username }}</el-descriptions-item>
          <el-descriptions-item label="真实姓名">{{ selectedUser.realName }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ selectedUser.email }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ selectedUser.phone }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(selectedUser.status)">
              {{ getStatusText(selectedUser.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="最后登录">{{ formatDate(selectedUser.lastLoginAt) }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(selectedUser.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDate(selectedUser.updatedAt) }}</el-descriptions-item>
        </el-descriptions>
        
        <div style="margin-top: 20px;">
          <h4>角色列表</h4>
          <el-tag
            v-for="userRole in selectedUser.userRoles"
            :key="userRole.role.id"
            size="small"
            style="margin-right: 8px; margin-bottom: 8px;"
          >
            {{ userRole.role.name }}
            <span style="color: #999; font-size: 12px;">{{ userRole.role.description }}</span>
          </el-tag>
        </div>
      </div>
    </el-dialog>

    <!-- 创建/编辑用户对话框 -->
    <el-dialog
      v-model="userFormVisible"
      :title="editingUser ? '编辑用户' : '创建用户'"
      width="500px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!editingUser">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="userForm.roleIds" multiple placeholder="请选择角色">
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="userFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { userApi, roleApi } from '@/api'
import { useUserStore } from '@/stores/user'
import type { User, Role } from '@/types'
import { formatDate } from '@/utils/format'
import { ALL_PERMISSIONS } from '@/constants/permissions'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const userList = ref<User[]>([])
const roleList = ref<Role[]>([])
const userDetailVisible = ref(false)
const userFormVisible = ref(false)
const selectedUser = ref<User | null>(null)
const editingUser = ref<User | null>(null)

// 搜索表单
const searchForm = reactive({
  search: '',
  status: '',
  roleId: ''
})

// 分页
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 用户表单
const userForm = reactive({
  username: '',
  email: '',
  password: '',
  realName: '',
  phone: '',
  roleIds: [] as number[]
})

// 表单验证规则
const userFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email' as const, message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ]
}

// 权限检查
const hasPermission = (permission: string) => {
  return userStore.hasPermission(permission)
}

const hasCreatePermission = computed(() => userStore.hasPermission(ALL_PERMISSIONS.USER_CREATE));
const hasEditPermission = computed(() => userStore.hasPermission(ALL_PERMISSIONS.USER_UPDATE));
const hasDeletePermission = computed(() => userStore.hasPermission(ALL_PERMISSIONS.USER_DELETE));
const hasEnablePermission = computed(() => userStore.hasPermission(ALL_PERMISSIONS.USER_ENABLE));
const hasDisablePermission = computed(() => userStore.hasPermission(ALL_PERMISSIONS.USER_DISABLE));
const hasResetPermission = computed(() => userStore.hasPermission(ALL_PERMISSIONS.USER_RESET));

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      ...searchForm
    }
    const response = await userApi.getUsers(params)
    userList.value = response.data.data
    pagination.total = response.data.pagination.total
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 获取角色列表
const fetchRoles = async () => {
  try {
    const response = await roleApi.getRoles({ limit: 100 })
    roleList.value = response.data.data
  } catch (error) {
    ElMessage.error('获取角色列表失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchUsers()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    search: '',
    status: '',
    roleId: ''
  })
  pagination.page = 1
  fetchUsers()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.limit = size
  pagination.page = 1
  fetchUsers()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchUsers()
}

// 查看用户详情
const handleView = (row: User) => {
  selectedUser.value = row
  userDetailVisible.value = true
}

// 创建用户
const handleCreate = () => {
  editingUser.value = null
  Object.assign(userForm, {
    username: '',
    email: '',
    password: '',
    realName: '',
    phone: '',
    roleIds: []
  })
  userFormVisible.value = true
}

// 编辑用户
const handleEdit = (row: User) => {
  editingUser.value = row
  Object.assign(userForm, {
    username: row.username,
    email: row.email,
    password: '',
    realName: row.realName || '',
    phone: row.phone || '',
    roleIds: row.userRoles?.map(ur => ur.roleId) || []
  })
  userFormVisible.value = true
}

// 启用用户
const handleEnable = async (row: User) => {
  try {
    await ElMessageBox.confirm(`确定要启用用户 ${row.username} 吗？`, '确认启用', {
      type: 'warning'
    })
    await userApi.enableUser(row.id)
    ElMessage.success('用户启用成功')
    fetchUsers()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('用户启用失败')
    }
  }
}

// 禁用用户
const handleDisable = async (row: User) => {
  try {
    await ElMessageBox.confirm(`确定要禁用用户 ${row.username} 吗？`, '确认禁用', {
      type: 'warning'
    })
    await userApi.disableUser(row.id)
    ElMessage.success('用户禁用成功')
    fetchUsers()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('用户禁用失败')
    }
  }
}

// 删除用户
const handleDelete = async (row: User) => {
  try {
    await ElMessageBox.confirm(`确定要删除用户 ${row.username} 吗？此操作不可恢复！`, '确认删除', {
      type: 'error'
    })
    await userApi.deleteUser(row.id)
    ElMessage.success('用户删除成功')
    fetchUsers()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('用户删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    if (editingUser.value) {
      await userApi.updateUser(editingUser.value.id, userForm)
      ElMessage.success('用户更新成功')
    } else {
      await userApi.createUser(userForm)
      ElMessage.success('用户创建成功')
    }
    userFormVisible.value = false
    fetchUsers()
  } catch (error) {
    ElMessage.error(editingUser.value ? '用户更新失败' : '用户创建失败')
  }
}

// 状态处理
const getStatusType = (status: string): 'success' | 'warning' | 'danger' | 'info' => {
  const statusMap: Record<string, 'success' | 'warning' | 'danger' | 'info'> = {
    'ACTIVE': 'success',
    'INACTIVE': 'warning',
    'BANNED': 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'ACTIVE': '启用',
    'INACTIVE': '禁用',
    'BANNED': '封禁'
  }
  return statusMap[status] || status
}

// 初始化
onMounted(() => {
  fetchUsers()
  fetchRoles()
})
</script>

<style scoped>
.user-list {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 